(function($) {
	$.m.app = {
	    initMessage : function() {
	        var messageBtn = $(".btn-message");
	        var icon = messageBtn.find(".icon-message");
	        var messageBtnInterval = null;

	        var activeUnreadIcon = function(count) {
	            clearInterval(messageBtnInterval);
	            if(count > 0) {
	                var label = messageBtn.find(".icon-count");
	                if(!label.length) {
	                    label = $("<i class='label label-important icon-count'></i>");
	                    messageBtn.append(label);
	                }
	                label.text(count);
	                messageBtn.addClass("unread");
	                messageBtnInterval = setInterval(function() {icon.toggleClass("icon-envelope-alt").toggleClass("icon-envelope");}, 650);
	            }
	        };

	        messageBtn.click(function() {
	            clearInterval(messageBtnInterval);
	            $($.find("#menu a:contains(我的消息)")).dblclick();
	            messageBtn.removeClass("unread");
	            messageBtn.find(".icon-count").remove();
	            icon.removeClass("icon-envelope").addClass("icon-envelope-alt");

	        });

	        activeUnreadIcon(messageBtn.data("unread"));

	        return {
	            update : function(unReadMessageCount) {
	                activeUnreadIcon(unReadMessageCount);
	            }
	        };
	    },
	    initNotification : function() {
	        var notificationBtn = $(".btn-notification");
	        var notificationList = $(".notification-list");
	        var menu = $(".notification-list .menu");
	        var menuList = menu.find(".list");
	        var detail = $(".notification-list .detail");
	        var detailList = detail.find(".list");
	        var loading = $(".notification-list .loading");
	        var noComment = $(".notification-list .no-comment");
	        var markReadUrl = _static + "/admin/personal/notification/markRead?id=";

	        var contentTemplate = '<li class="view-content {unread}"><span>{title}</span><span class="pull-right">{date}</span></li>';
	        var detailContentTemplate = '<div id="notificaiton-{id}" class="notification-detail" style="display: none"><div class="title"><span>{title}</span><span class="pull-right">{date}</span></div><div class="content">{content}</div></div>';
	        var moreContent = '<li class="view-all-notification"><span>&gt;&gt;查看所有通知</span></li>';

	        var viewAllNotification = function() {
	            $($.find("#menu a:contains(我的通知)")).dblclick();
	            hideNotification();
	            return false;
	        };
	        var hideNotification = function() {
	            notificationList.find(".content > div").hide();
	            notificationList.removeClass("in");
	            $("body")
	                .off("click")
	                .find("iframe").contents().find("body").each(function() {
	                    $(this).off("click");
	                });
	        };

	        var activeDetailBtn = function() {
	            var notificationDetails = detail.find(".notification-detail");
	            var current = notificationDetails.not(":hidden");
	            var currentIndex = notificationDetails.index(current);

	            var pre = detail.find(".pre");
	            var next = detail.find(".next");
	            pre.removeClass("none");
	            next.removeClass("none");


	            if(currentIndex == 0) {
	                pre.addClass("none");
	            }

	            var currentMenu = $(menu.find(".view-content").get(currentIndex));
	            if(currentMenu.hasClass("unread")) {
	                currentMenu.removeClass("unread");
	                var id = current.attr("id").replace("notificaiton-", "");
	                $.ajax({
	                    url: markReadUrl + id,
	                    global: false,
	                    error: function (xmlHR, textStatus, errorThrown) {
	                        //ignore
	                    }
	                });
	            }

	            if(currentIndex == notificationDetails.length - 1) {
	                next.addClass("none");
	            }

	        };

	        var showNoComment = function() {
	            notificationList.find(".content > div").hide();
	            noComment.show();
	        };
	        var showMenu = function() {
	            notificationList.find(".content > div").hide();
	            menu.show();
	        };


	        var initDetail = function(dataList) {
	            var content = "";
	            $(dataList).each(function(index, data) {
	                content = content + detailContentTemplate.replace("{id}", data.id).replace("{title}", data.title).replace("{date}", data.date).replace("{content}", data.content);
	            });
	            detailList.html(content);
	            detail.find(".notification-detail:first").show();
	            detail.find(".back-notification-list").click(function() {
	                slide(detail, menu, "left");
	            });
	            detail.find(".pre").click(function() {
	                var current = detail.find(".notification-detail").not(":hidden");
	                var pre = current.prev(".notification-detail");
	                if (pre.length) {
	                    slide(current, pre, "left");
	                }
	            });
	            detail.find(".next").click(function() {
	                var current = detail.find(".notification-detail").not(":hidden");
	                var next = current.next(".notification-detail");
	                if (next.length) {
	                    slide(current, next, "right");
	                }
	            });
	            slide(menu, detail, "right");

	            return false;
	        };



	        var initMenu = function(dataList, hasUnread) {

	            var content = "";
	            $(dataList).each(function (index, data) {
	                content = content + contentTemplate.replace("{unread}", data.read ? "" : "unread").replace("{title}", data.title).replace("{date}", data.date);
	            });
	            content = content + moreContent;
	            menuList.html(content);

	            menu.find(".view-content").click(function() {
	                initDetail(dataList);
	            });
	            menu.find(".view-all-notification").click(function() {
	                viewAllNotification();
	            });

	            if(hasUnread) {
	                showNotification();
	            }

	            return false;
	        };
	        var slide = function(from, to, direction) {
	            from.css({
	                position: 'relative',
	                width:"100%"
	            });
	            from.stop(true).hide("slide", {direction : direction == "left" ? "rigth" : "left"}, function() {
	                from.css({
	                    position : "",
	                    width : "",
	                    left : ""
	                });
	            });
	            to.css({
	                position: 'absolute',
	                top: to.is(".notification-detail") ? to.closest(".detail").find(".title").outerHeight() + "px" : "0px",
	                left: "0px",
	                width: "100%",
	                display : "none"
	            });
	            to.stop(true).show("slide", {direction : direction}, function() {
	                to.css({
	                    position : "",
	                    left : "",
	                    top : "",
	                    width : ""
	                });
	                if(to.is(".notification-detail") || to.is(".detail")) {
	                    activeDetailBtn();
	                }
	            });
	        };

	        var showNotification = function() {
	            notificationList.addClass("in");

	            var windowClickHideNotification = function (event) {
	                var target = $(event.target);
	                if (!target.closest(".btn-notification").length && !target.closest(".notification-list").length) {
	                    hideNotification();
	                }
	            };

	            $("body")
	                .on("click", windowClickHideNotification)
	                .find("iframe").contents().find("body").each(function() {
	                    $(this).on("click", windowClickHideNotification);
	                });
	            if(menu.find(".view-content").length) {
	                showMenu();
	            } else {
	                showNoComment();
	            }
	        };

	        notificationBtn.click(function() {
	            if(notificationList.hasClass("in")) {
	                hideNotification();
	            } else {
	                showNotification();
	            }
	        });
	        notificationList.find(".close-notification-list").click(function() {
	            hideNotification();
	        });

	        hideNotification();

	        return {
	            update : function(dataList) {

	                if(!dataList.length) {
	                    showNoComment();
	                    return;
	                }

	                var hasUnread = false;
	                for(var i = 0, l = dataList.length; i < l; i++) {
	                    var data = dataList[i];
	                    if(!data.read) {
	                        hasUnread = true;
	                        data.title = data.title.replace("{ctx}", _static);
	                        data.content = data.content.replace("{ctx}", _static);
	                    }
	                }

	               initMenu(dataList, hasUnread);

	            }
	        };
	    },
	    /**
	     * 异步加载url内容到tab
	     */
	    loadingToCenterIframe: function (panel, url, loadingMessage, forceRefresh) {
	        panel.data("url", url);

	        var panelId = panel.prop("id");
	        var iframeId = "iframe-" + panelId;
	        var iframe = $("#" + iframeId);

	        if (!iframe.length || forceRefresh) {
	            if(!iframe.length) {
	                iframe = $("iframe[tabs=true]:last").clone(true);
	                iframe.prop("id", iframeId);
	                $("iframe[tabs=true]:last").after(iframe);
	            }

	            $.m.app.waiting(loadingMessage);
	            iframe.prop("src", url).one("load", function () {
	                $.m.app.activeIframe(panelId, iframe);
	                $.m.app.waitingOver();
	            });

	        } else {
	            $.m.app.activeIframe(panelId, iframe);
	        }

	    },
	    activeIframe: function (panelId, iframe) {
	        if (!iframe) {
	            iframe = $("#iframe-" + panelId);
	        }
	        var layout = $.layouts.layout;
	        if (layout.panes.center.prop("id") == iframe.prop("id")) {
	            return;
	        }
	        layout.panes.center.hide();
	        layout.panes.center = iframe;
	        layout.panes.center.show();
	        layout.resizeAll();
	        $.tabs.initTabScrollHideOrShowMoveBtn(panelId);
	    },

	    waiting : function(message, isSmall) {
	        if(!message) {
	            message = "装载中...";
	        }

	        message = '<img src="' + _static + '/static/img/loading.gif" '+ (isSmall ? "width='20px'" : "") +'/> ' + message;
	        if(!isSmall) {
	            message = "<h4>"+message+"</h4>";
	        }
	        $.blockUI({
	            fadeIn: 700,
	            fadeOut: 700,
	            showOverlay: false,
	            css: {
	                border: 'none',
	                padding: '15px',
	                backgroundColor: '#eee',
	                '-webkit-border-radius': '10px',
	                '-moz-border-radius': '10px',
	                opacity:1,
	                color: '#000',
	                width: isSmall ? "40%" : "30%"

	            },
	            message: message
	        });
	    }
	    ,
	    waitingOver: function () {
	        $.unblockUI();
	    }
	    ,
	    /**
	     * 当前显示的模态窗口队列
	     */
	    _modalDialogQueue:null,
	    /**
	     * 模态窗口
	     * @title 标题
	     * @param url
	     * @param settings
	     */
	    modalDialog : function(title, url, settings) {

	        $.m.app.waiting();
	        var ok = $.i18n.ok;
	        var cancel = $.i18n.cancel;
	        var defaultSettings = {
	            title : title,
	            closeText : $.i18n.close,
	            closeOnEscape:false,
	            height:300,
	            width:600,
	            modal:true,
	            noTitle : false,
	            close: function() {
	                $(this).closest(".ui-dialog").remove();
	            },
	            _close : function(modal) {
	                $(modal).dialog("close");
	                if($.m.app._modalDialogQueue.length > 0) {
	                    $.m.app._modalDialogQueue.pop();
	                }
	            },
	            buttons:{
	            	'确认': function() {
	                    if(settings.ok) {
	                        /*if(settings.ok($(this))) {
	                            settings._close(this);
	                        }*/
	                    	//不需要ok返回true再关闭，个人觉得
	                    	settings.ok($(this));
	                    	settings._close(this);
	                    } else {
	                        settings._close(this);
	                    }
	                    if(settings.callback) {
	                        settings.callback();
	                    }
	                },
	                '关闭': function () {
	                    settings._close(this);
	                    if(settings.callback) {
	                        settings.callback();
	                    }
	                }
	            }
	        };
	        if(!settings) {
	            settings = {};
	        }
	        settings = $.extend(true, {}, defaultSettings, settings);

	        if(!settings.ok) {
	            delete settings.buttons[$.i18n.ok];
	        }

	        $.ajax({
	            url: url,
	            //headers: { table:true }
	        }).done(function (data) {
	                $.m.app.waitingOver();
	                var div = $("<div></div>").append(data);
	                var dialog = div.dialog(settings)
	                    .closest(".ui-dialog").data("url", url).removeClass("ui-widget-content")
	                    .find(".ui-dialog-content ").removeClass("ui-widget-content").focus();

	                if(settings.noTitle) {
	                    dialog.closest(".ui-dialog").find(".ui-dialog-titlebar").addClass("no-title");
	                }
	                dialog.closest(".ui-dialog").focus();
	                if(!$.m.app._modalDialogQueue) {
	                    $.m.app._modalDialogQueue = new Array();
	                }
	                $.m.app._modalDialogQueue.push(dialog);
	                $.m.table.initTable(div.find(".table"));

//				            $.blockUI({
//				                url : url,
//				                theme:true,
//				                showOverlay : true,
//				                title : title,
//				                message : data,
//				                css : css,
//				                themedCSS: css
//				            });


	            });
	    }
	    ,
	    /**
	     * 取消编辑
	     */
	    cancelModelDialog : function() {
	        if($.m.app._modalDialogQueue && $.m.app._modalDialogQueue.length > 0) {
	            $.m.app._modalDialogQueue.pop().dialog("close");
	        }
	    }
	    ,
	    alert : function(options) {
	        if(!options) {
	            options = {};
	        }
	        if(typeof options === 'string'){
	        	options = {
	        		message: options
	        	}
	        }
	        var defaults = {
	            title : $.i18n.alert,
	            message : $.i18n.illegalOperation,
	            okTitle : $.i18n.close,
	            ok : $.noop
	        };
	        options.alert = true;
	        options = $.extend({}, defaults, options);
	        this.confirm(options);
	    }
	    ,
	    /**
	     * 格式
	     * @param options
	     */
	    confirm : function(options) {
	        var defaults = {
	            title : $.i18n.confirm,
	            message : $.i18n.confirmToOperate,
	            cancelTitle : $.i18n.cancel,
	            okTitle : $.i18n.ok,
	            cancel : $.noop,
	            ok : $.noop,
	            alert : false
	        };

	        if(!options) {
	            options = {};
	        }
	        options = $.extend({}, defaults, options);

	        var template = '<div class="modal fade draggable-modal modal_wrapper" id="basic" tabindex="-1" role="basic" aria-hidden="true">'+
	        '    <div class="modal-dialog">'+
	        '	<div class="modal-content">'+
	        '	    <div class="modal-header">'+
	        '		<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>'+
	        '		<h4 class="modal-title">{title}</h4>'+
	        '	    </div>'+
	        '	    <div class="modal-body"> {message} </div>'+
	        '	    <div class="modal-footer">'+
	        '		<button type="button" class="btn dark btn-outline btn-cancel" data-dismiss="modal">{cancelTitle}</button>'+
	        '		<button type="button" class="btn green btn-ok" data-dismiss="modal">{okTitle}</button>'+
	        '	    </div>'+
	        '	</div>'+
	        '    </div>'+
	        '</div>';
	        var modalDom =
	            $(template
	                .replace("{title}", options.title)
	                .replace("{message}", options.message)
	                .replace("{cancelTitle}", options.cancelTitle)
	                .replace("{okTitle}", options.okTitle));

	        var hasBtnClick = false;
	        if(options.alert) {
	            modalDom.find(".modal-footer > .btn-cancel").remove();
	        } else {
	            modalDom.find(".modal-footer > .btn-cancel").click(function() {
	                hasBtnClick = true;
	                options.cancel();
	            });
	        }
	        modalDom.find(".modal-footer > .btn-ok").click(function() {
	            hasBtnClick = true;
	            options.ok();
	        });

	        modalDom.find(".modal-dialog").draggable({
	            handle: ".modal-header"
	        });
	        
	        var modal = modalDom.modal();

	        modal.on("hidden", function() {
	            modal.remove();//移除掉 要不然 只是hidden
	            if(hasBtnClick) {
	                return true;
	            }
	            if(options.alert) {
	                options.ok();
	            } else {
	                options.cancel();
	            }
	        });
	        
	        return modal;
	    },
	    isImage : function(filename) {
	        return /gif|jpe?g|png|bmp$/i.test(filename);
	    },
	    initDatetimePicker : function() {
	        //初始化 datetime picker
	    	var config = {
	    			format: "yyyy-mm-dd",
	    			autoclose : true,
	    			maskInput: true,
	    			orientation: "bottom-left",
	    			language:"zh-CN"
	    	};
	        $('.date').each(function() {
	            var $date = $(this);

	            if($date.attr("initialized") == "true") {
	                return;
	            }
	            
	            var pickDate = $(this).find("[data-format]").data("format").toLowerCase().indexOf("yyyy-mm-dd") != -1;
	            var pickTime = $(this).find("[data-format]").data("format").toLowerCase().indexOf("hh:mm:ss") != -1;
	            $date.datetimepicker(config);
	            $date.find(":input").click(function() {$date.find(".icon-calendar,.icon-time,.icon-date").click();});
	            $date.attr("initialized", true);
	        });
	    },
	    removeContextPath : function(url) {
	        if(url.indexOf(_static) == 0) {
	            return url.substr(_static.length);
	        }
	        return url;
	    },
	    /**
	     * 异步化form表单或a标签
	     * @param $form
	     * @param containerId
	     */
	    asyncLoad : function($tag, containerId) {
	        if($tag.is("form")) {
	            $tag.submit(function() {
	                if($tag.prop("method").toLowerCase() == 'post') {
	                    $.post($tag.prop("action"), $tag.serialize(), function(data) {
	                        $("#" + containerId).replaceWith(data);
	                    });
	                } else {
	                    $.get($tag.prop("action"), $tag.serialize(), function(data) {
	                        $("#" + containerId).replaceWith(data);
	                    });
	                }
	                return false;
	            });
	        } else if($tag.is("a")) {
	            $tag.click(function() {
	                $.get($tag.prop("href"), function(data) {
	                    $("#" + containerId).replaceWith(data);
	                });
	                return false;
	            });
	        } else {
	            $.m.app.alert({message : "该标签不支持异步加载，支持的标签有form、a"});
	        }

	    },
	    
	    asyncSubmit : function(config){
	    	var defaultConfig = {
	    	};
	    	config = $.extend(true, defaultConfig, config);
	    	var $form = $(config.form);
	    	if($form.is("form")){
	    		var action = $form.prop("action");
	    		if(action == null){
	    			action = config.action;
	    		}
	    		if($form.prop("method").toLowerCase() == 'post') {
                    $.post(action, "ajax=true&" + $form.serialize(), function(data) {
	                    if(config.callback) {
	                    	config.callback(data);
	                    }
                    });
                } else {
                    $.get(action, "ajax=true&" + $form.serialize(), function(data) {
                    	if(config.callback) {
	                    	config.callback(data);
	                    }
                    });
                }
	    	}else {
	            $.m.app.alert({message : "该标签不支持异步提交，支持的标签有form"});
	        }
	    },
	    /**
	     * 只读化表单
	     * @param form
	     */
	    readonlyForm : function(form, removeButton) {
	        var inputs = $(form).find(":input");
	        inputs.not(":submit,:button").prop("readonly", true);
	        if(removeButton) {
	            inputs.remove(":button,:submit");
	        }
	        $(form).find("select,input:radio,input:checkbox").prop("disabled",true);
	    },

	    /**
	     * 将$("N").val() ----> [1,2,3]
	     */
	    joinVar : function(elem, separator) {
	        if(!separator) {
	            separator = ",";
	        }
	        var array = new Array();
	        $(elem).each(function() {
	            array.push($(this).val());
	        });

	        return array.join(separator);
	    },

	    /**
	     * 异步加载table子内容(父子表格)
	     * @param toggleEle
	     * @param tableEle
	     * @param asyncLoadURL
	     */
	    toggleLoadTable : function(tableEle, asyncLoadURL) {
	        var openIcon = "icon-plus-sign";
	        var closeIcon = "icon-minus-sign";
	        $(tableEle).find("tr .toggle-child").click(function() {
	            var $a = $(this);
	            //只显示当前的 其余的都隐藏
	            $a.closest("table")
	                .find(".toggle-child." + closeIcon).not($a).removeClass(closeIcon).addClass(openIcon)
	                .end().end()
	                .find(".child-data").not($a.closest("tr").next("tr")).hide();

	            //如果是ie7
	            if($(this).closest("html").hasClass("ie7")) {
	                var $aClone = $(this).clone(true);
	                if($aClone.hasClass(closeIcon)) {
	                    $aClone.addClass(openIcon).removeClass(closeIcon);
	                } else {
	                    $aClone.addClass(closeIcon).removeClass(openIcon);
	                }
	                $(this).after($aClone);
	                $(this).remove();
	                $a = $aClone;
	            } else {
	                $a.toggleClass(openIcon);
	                $a.toggleClass(closeIcon);
	            }

	            var $currentTr = $a.closest("tr");
	            var $dataTr = $currentTr.next("tr");
	            if(!$dataTr.hasClass("child-data")) {
	                $.m.app.waiting();
	                $dataTr = $("<tr class='child-data' style='display: none;'></tr>");
	                var $dataTd = $("<td colspan='" + $currentTr.find("td").size() + "'></td>");
	                $dataTr.append($dataTd);
	                $currentTr.after($dataTr);
	                $dataTd.load(asyncLoadURL.replace("{parentId}", $a.data("id")),function() {
	                    $.m.app.waitingOver();
	                });
	            }
	            $dataTr.toggle();

	            return false;
	        });

	    },

	    initAutocomplete : function(config) {
	    	// Metronic5中没有jquery-ui-autocomplete插件，所以用typeahead来替代
            // https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md
	        var defaultConfig = {
	            minLength : 1,
                hint: false,
                highlight: true,
	            enterSearch : false,
                source: "" // url to fetch remote data
	        };

	        config = $.extend(true, defaultConfig, config);

            $(config.input).typeahead(config,{
				source: function (query, process, asyncProcess) {
					return $.ajax({
						url: config.source,
						type: 'post',
						data: {term: query},
						dataType: 'json',
						success: function (result) {
							return asyncProcess(result);
						}
					});
				}
			})
			.on( "keydown", function( event ) {
				//回车查询
				if(config.enterSearch && event.keyCode === 13) {
					config.select(event, {item:{value:$(this).val()}});
				}
            }).bind('typeahead:change', function (e, value) {
            }).bind('typeahead:select', function (e, suggestion) {
                config.select(event, {item:{value:suggestion}});
            });
	    }
	};
	
	$.movable = {
	    /**
	     * urlPrefix：指定移动URL的前缀，
	     * 如/sample，生成的URL格式为/sample/{fromId}/{toId}/{direction:方向(up|down)}
	     * @param table
	     * @param urlPrefix
	     */
	    initMoveableTable : function(table) {
	        if(!table.length) {
	            return;
	        }
	        var urlPrefix = table.data("move-url-prefix");
	        if(!urlPrefix) {
	            $.m.app.alert({message : "请添加移动地址URL，如&lt;table move-url-prefix='/sample'&gt;<br/>自动生成：/sample/{fromId}/{toId}/{direction:方向(up|down)}"});
	        }
	        var fixHelper = function (e, tr) {
	            var $originals = tr.children();
	            var $helper = tr.clone();
	            $helper.children().each(function (index) {
	                // Set helper cell sizes to match the original sizes
	                $(this).width($originals.eq(index).width())
	            });
	            return $helper;
	        };

	        //事表格可拖拽排序
	        table.find("tbody")
	            .sortable({
	                helper: fixHelper,
	                opacity: 0.5,
	                cursor: "move",
	                placeholder: "sortable-placeholder",
	                update: function (even, ui) {
	                    even.stopPropagation();
	                    prepareMove(ui.item.find(".moveable").closest("td"));
	                }
	            });

	        //弹出移动框
	        table.find("a.pop-movable[rel=popover]")
	            .mouseenter(function (e) {
	                var a = $(this);
	                a.popover("show");
	                var idInput = a.closest("tr").find(".id");
	                idInput.focus();
	                a.next(".popover").find(".popover-up-btn,.popover-down-btn").click(function() {
	                    var fromId = $(this).closest("tr").prop("id");
	                    var toId = idInput.val();

	                    if(!/\d+/.test(toId)) {
	                        $.m.app.alert({message : "请输入数字!"});
	                        return;
	                    }

	                    var fromTD = $(this).closest("td");

	                    if($(this).hasClass("popover-up-btn")) {
	                        move(fromTD, fromId, toId, "up");
	                    } else {
	                        move(fromTD, fromId, toId, "down");
	                    }
	                });
	                a.parent().mouseleave(function() {
	                    a.popover("hide");
	                });
	            });

	        table.find(".up-btn,.down-btn").click(function() {
	            var fromTR = $(this).closest("tr");
	            if($(this).hasClass("up-btn")) {
	                fromTR.prev("tr").before(fromTR);
	            } else {
	                fromTR.next("tr").after(fromTR);
	            }
	            prepareMove($(this).closest("td"));
	        });

	        /**
	         *
	         * @param fromTD
	         */
	        function prepareMove(fromTD) {
	            var fromTR = fromTD.closest("tr");
	            var fromId = fromTR.prop("id");
	            var nextTR = fromTR.next("tr");
	            if(nextTR.length) {
	                move(fromTD, fromId, nextTR.prop("id"), "down");
	            } else {
	                var preTR = fromTR.prev("tr");
	                move(fromTD, fromId, preTR.prop("id"), "up");
	            }

	        }
	        function move(fromTD, fromId, toId, direction) {
	            if(!(fromId && toId)) {
	                return;
	            }
	            var order = $.movable.tdOrder(fromTD);
	            if (!order) {
	                $.m.app.alert({message: "请首先排序要移动的字段！"});
	                return;
	            }
	            //如果升序排列 需要反转direction
	            if(order == "desc") {
	                if(direction == "up") {
	                    direction = "down";
	                } else {
	                    direction = "up";
	                }
	            }
	            $.m.app.waiting("正在移动");
	            var url = urlPrefix + "/" + fromId + "/" + toId + "/" + direction;
	            $.getJSON(url, function(data) {
	                $.m.app.waitingOver();
	                if(data.success) {
	                    $.m.table.reloadTable(fromTD.closest("table"));
	                } else {
	                    $.m.app.alert({message : data.message});
	                }

	            });
	        }
	    },
	    initMovableReweight : function($btn, url) {
	        $btn.click(function () {
	            $.m.app.confirm({
	                message: "确定优化权重吗？<br/><strong>注意：</strong>优化权重执行效率比较低，请在本系统使用人员较少时执行（如下班时间）",
	                ok: function () {
	                    $.m.app.waiting("优化权重执行中。。");
	                    $.getJSON(url, function(data) {
	                        $.m.app.waitingOver();
	                        if(!data.success) {
	                            $.m.app.alert({message : data.message});
	                        } else {
	                            location.reload();
	                        }
	                    });
	                }
	            });
	        });
	    },

	    tdOrder : function(td) {
	        var tdIndex = td.closest("tr").children("td").index(td);
	        return td.closest("table").find("thead > tr > th").eq(tdIndex).prop("order");
	    }
	};
	
	$.m.btn = {
	    initChangeStatus : function(urlPrefix, tableId, config) {
	        $(config.btns.join(",")).each(function(i) {
	            $(this).off("click").on("click", function() {
	                var $table = $("#" + tableId);
	                var checkbox = $.m.table.getAllSelectedCheckbox($table);
	                if(checkbox.size() == 0) {
	                    return;
	                }
	                var title = config.titles[i];
	                var message = config.messages[i];
	                var status = config.status[i];
	                var param = "status";
	                if(config.param){
	                	param = config.param;
	                }
	                var url = urlPrefix + "/changeStatus.html?" + param + "=" + status + "&" + checkbox.serialize() + "&BackURL=" + $.m.table.encodeTableURL($table);
	                $.m.app.confirm({
	                    title : title,
	                    message : message,
	                    ok : function() {
	                        window.location.href = url;
	                    }
	                });
	            });
	        });
	    },
	    /**
	     * 初始化改变显示隐藏的btn
	     */
	    initChangeShowStatus : function(urlPrefix, tableId) {
	        $.m.btn.initChangeStatus(urlPrefix, tableId, {
	        	param : "show", 
	            btns : [".status-show", ".status-hide"],
	            titles : ['显示选中数据', '隐藏选中数据'],
	            messages : ['确认显示选中数据吗？', '确认隐藏选中数据吗？'],
	            status : ['true', 'false']
	        });
	    },
	    /**
	     * 初始化改变激活，冻结的btn
	     */
	    initChangeActivatedStatus : function(urlPrefix, tableId) {
	        $.m.btn.initChangeStatus(urlPrefix, tableId, {
	        	param : "activated", 
	            btns : [".status-activate", ".status-deactivate"],
	            titles : ['激活选中数据', '冻结选中数据'],
	            messages : ['确认激活选中数据吗？', '确认冻结数据吗？'],
	            status : ['true', 'false']
	        });
	    },
	    /**
	     * 初始化改变删除，恢复的btn
	     */
	    initChangeDeletedStatus : function(urlPrefix, tableId) {
	        $.m.btn.initChangeStatus(urlPrefix, tableId, {
	        	param : "deleted", 
	            btns : [".status-delete", ".status-recycle"],
	            titles : ['删除选中数据', '恢复选中数据'],
	            messages : ['确认删除选中数据吗？', '确认恢复数据吗？'],
	            status : ['true', 'false']
	        });
	    }
	};
	
	$.m.app.initIconPicker = function($ele){
    	var eleId = $ele.attr("id");
    	var pickerId = "icon-picker-"+eleId;
    	$ele.before('<button type="button" id="'+pickerId+'" class="btn btn-default" role="iconpicker"></button>');
    	$(pickerId).iconpicker({ 
    	    //align: 'center', // Only in div tag
    	    arrowClass: 'btn-danger',
    	    //arrowPrevIconClass: 'glyphicon glyphicon-chevron-left',
    	    //arrowNextIconClass: 'glyphicon glyphicon-chevron-right',
    	    cols: 10,
    	    footer: true,
    	    header: true,
    	    icon: 'fa-bomb',
    	    iconset: 'fontawesome',   
    	    labelHeader: '{0} of {1} pages',
    	    labelFooter: '{0} - {1} of {2} icons',
    	    placement: 'bottom', // Only in button tag
    	    rows: 5,
    	    search: true,
    	    searchText: 'Search',
    	    selectedClass: 'btn-success',
    	    unselectedClass: ''
    	});
    	
    	$(pickerId).on('change', function(e) { 
    		$ele.val(e.icon);
	    });
    }
	
	$.m.app.showMenu = function(menuId){
		if(menuId!=null&&menuId!=''){
			// clear active state
			var $siderbar = $(".page-sidebar-menu")
			var $horMenu = $(".hor-menu")
			$siderbar.find("li.nav-item").removeClass("active").removeClass("open");
			$siderbar.find("a.nav-link span").removeClass("open");
			$horMenu.find("li.classic-menu-dropdown").removeClass("active");
			
    		menuId = menuId.replace("\.","\\."); //resolve id contains dot issue
    		var $currentMenu = $("a.nav-link#menu_"+menuId);
    		var relatedMenus = $currentMenu.parents("li.nav-item");
    		relatedMenus.addClass("active open");
    		relatedMenus.find("a.nav-link span").addClass("open");
    		
    		if($horMenu[0]){
    			$("a#hor_menu_"+menuId).parents("li.classic-menu-dropdown").addClass("active")
    			var groupId = relatedMenus.first().data("menu-group");
    			$siderbar.find("li[data-menu-group!='"+groupId+"']").hide();
    			$siderbar.find("li[data-menu-group='"+groupId+"']").show();
    			$siderbar.find("li.heading").hide();
    		}
    		$siderbar.show();
		}
	}
	$.m.app.initMenuHighLight = function(){
		// hightlight a certain menu when finish loading
		var current_menu_code = $("#menu_code").val();
		if(current_menu_code==null||current_menu_code==''){
			if(location.hash!=null){
				current_menu_code = $("#menu_code_" + location.hash.split("#")[1]).val();
			}
		}
		$.m.app.showMenu(current_menu_code);
		$(".hor-menu,.page-sidebar-menu").find("a[data-pjax]").click(function(){
			$.m.app.showMenu($(this).data("menu-code"));
		})
	}

	$.m.app.initConfirmation = function(){
        $('[data-toggle=confirmation],[data-confirmation=true]').bind('click', function (e) {
            var $ele = $(this);
            var config = $ele.data();
            $.m.confirm({
                text: config.originalTitle,
                confirmButtonText: config.btnOkLabel ? config.btnOkLabel : $.i18n.ok,
                cancelButtonText: config.btnCancelLabel ? config.btnCancelLabel : $.i18n.cancel,
                ok: function () {
                    if ($ele.is("a") && $ele.attr("href")) {
                        window.location.href = $ele.attr("href");
                    } else if($ele.is("button") && $ele.is("[type=submit]")){
						// $ele.click();
                        $ele.closest("form").submit();
					}
                }
            });
            // 阻止默认行为
            if (e && e.preventDefault) {
                //如果是FF下执行这个
                e.preventDefault();
            } else {
                //如果是IE下执行这个
                window.event.returnValue = false;
            }
        });
	}
})(jQuery);


jQuery(function($){
	//global disable ajax cache
    //$.ajaxSetup({ cache: true });

    /*$(".dataTable").each(function() {
       $.m.table.initTable($(this));
    });*/
	$.m.app.initMenuHighLight();

	$.m.app.initConfirmation();
});
